// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use expect_test::expect;
use std::{fs::File, io::Read, path::PathBuf};

use sui_move::manage_package::ManagePackage;
use sui_move_build::BuildConfig;
use sui_types::base_types::ObjectID;

#[tokio::test]
async fn test_manage_package_update() {
    let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    path.extend(["src", "unit_tests", "data", "basic_no_deps"]);

    let tmp = tempfile::tempdir().expect("Could not create temp dir for Move.lock");
    let lock_file_path = tmp.path().join("Move.lock");

    let mut build_config = BuildConfig::new_for_testing();
    build_config.config.lock_file = Some(lock_file_path.clone());
    build_config
        .clone()
        .build(&path)
        .expect("Move package did not build");
    // Update the lock file with placeholder compiler version so this isn't bumped every release.
    build_config
        .config
        .update_lock_file_toolchain_version(&path, "0.0.1".into())
        .expect("Could not update lock file");

    let original_id = ObjectID::from_hex_literal("0xa").unwrap();
    let latest_id = ObjectID::from_hex_literal("0xb").unwrap();

    let manage_package = ManagePackage {
        environment: "mainnet".to_string(),
        chain_id: "12345".to_string(),
        original_id,
        latest_id,
        version_number: 5,
    };
    let _ = manage_package.execute(Some(&lock_file_path), build_config.config);

    let mut lock_file_contents = String::new();
    File::open(lock_file_path)
        .expect("Cannot open lock file")
        .read_to_string(&mut lock_file_contents)
        .expect("Error reading Move.lock file");

    let expected = expect![[r##"
        # @generated by Move, please check-in and do not edit manually.

        [move]
        version = 3
        manifest_digest = "919A5B078B47AD46674F36E1605578927D5BC4536A7646D78D1320A25DDD57CC"
        deps_digest = "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"

        [move.toolchain-version]
        compiler-version = "0.0.1"
        edition = "2024.beta"
        flavor = "sui"

        [env]

        [env.mainnet]
        chain-id = "12345"
        original-published-id = "0x000000000000000000000000000000000000000000000000000000000000000a"
        latest-published-id = "0x000000000000000000000000000000000000000000000000000000000000000b"
        published-version = "5"
    "##]];
    expected.assert_eq(lock_file_contents.as_str());
}
